from django.shortcuts import render, HttpResponse
from utils.tencent.sms import send_sms_single
import random
from django.conf import settings
from django import forms
from . import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


# 发送短信功能
def sms_send(request):
    """发送短信"""
    """判断短信类型"""
    tql = request.GET.get('tql')
    template_id = settings.TEMPLATES.get(tql)
    if not template_id:
        return HttpResponse('不存在')

    code = random.randint(1000, 9999)
    res = send_sms_single('15877248614', template_id, [code, ])
    if res['result'] == 0:
        return HttpResponse("成功")
    else:
        return HttpResponse(res['errmsg'])
    return HttpResponse("成功")


# 注册功能
class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label="手机号", validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机格式错误'), ])
    password = forms.CharField(label="密码", widget=forms.PasswordInput())
    comfirm_password = forms.CharField(label="重复密码", widget=forms.PasswordInput())
    code = forms.CharField(label="验证码")

    class Meta:
        model = models.UserInfo
        fields = ["username", "email", "password", "comfirm_password", "mobile_phone", "code"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args,**kwargs)
        for name, field in self.fields.items():
            field.widget.attrs["class"] = "form-control"
            field.widget.attrs["placeholder"] = "请输入{}".format(field.label)


def register(request):
    form = RegisterModelForm
    return render(request, "app01/register.html", {"form": form})

def test(request):
    return render(request,"app01/test.html")